# -*- coding:utf-8 -*-
from flask import request,abort,current_app,jsonify,make_response,json
from . import api
from ihome.utils.captcha.captcha import captcha
from ihome import redis_store
from ihome import constants
from ihome.utils.response_code import RET
import re,random
from ihome.utils.sms import CCP
from ihome.models import User

@api.route('/imagecode')
def get_image_code():
    ''''''
    ages = request.args
    cur = ages.get('cur')
    pre = ages.get('pre')

    print cur
    if not cur:
        abort(403)

    _, text, image = captcha.captcha.generate_captcha()
    print text
    try:
        if pre:
            redis_store.delete('ImageCode_'+pre)

        redis_store.set('ImageCode_'+cur, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '保存失败')

    respnose = make_response(image)

    respnose.headers['Content-Type'] = "image/jpg"
    return respnose

@api.route('/sms',methods=['POST'])
def send_sms():
    # data = request.data
    # data_dict = json.loads(data)
    data_dict = request.get_json()
    mobile = data_dict.get('mobile')
    image_code = data_dict.get('image_code')
    image_code_id = data_dict.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不完整')

    if not re.match("^1[345678][0-9]{9}$",mobile):
        return jsonify(errno = RET.PARAMERR,errmsg = '手机号格式不正确')

    try:
        real_image_code = redis_store.get("ImageCode_"+image_code_id)
        redis_store.delete("ImageCode_"+image_code_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '获取验证码失败')

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg='获取验证码过期')

    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='输入验证码不正确')


    try:
        user = User.query.filter(mobile = mobile).first()
    except Exception as e:
        user = None
        current_app.logger.error(e)

    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机号已经注册')

    result = random.randint(0,999999)
    sms_code = "%06d"%result
    current_app.logger.debug(sms_code)
    result = CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES/60],"1")
    if result == 0:
       return jsonify(errno=RET.THIRDERR, errmsg='发送验证码失败')

    try:
        redis_store.set('SMS_'+mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='保存证码失败')

    return jsonify(errno = RET.OK,errmsg= '发送验证码成功')